################################################################################
#	Copyright (C) 2012-2013 Fernando "Franz" Zapata
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
################################################################################

find_program (GRESOURCE_COMPILE_EXECUTABLE glib-compile-resources)

include (FindPackageHandleStandardArgs)
find_package_handle_standard_args (GResource
	REQUIRED_VARS GRESOURCE_COMPILE_EXECUTABLE
)

include (CMakeParseArguments)

function (glib_compile_resources output)
	cmake_parse_arguments (ARGS "" "SOURCEDIR;OUTDIR;CNAME" "" ${ARGN})

	if (ARGS_SOURCEDIR)
		set (SOURCEDIR ${ARGS_SOURCEDIR})
	else ()
		set (SOURCEDIR ${CMAKE_CURRENT_SOURCE_DIR})
	endif ()

	if (ARGS_OUTDIR)
		set (OUTDIR ${ARGS_OUTDIR})
	else ()
		set (OUTDIR ${CMAKE_CURRENT_BINARY_DIR})
	endif ()

	set (OUT_C)
	foreach (src ${ARGS_UNPARSED_ARGUMENTS})
		string (REGEX MATCH "^/" matched ${src})
		if (matched MATCHES "/")
			set (in_file ${src})
		else ()
			set (in_file ${CMAKE_CURRENT_SOURCE_DIR}/${src})
		endif ()
		get_filename_component (filename ${in_file} NAME)
		string (REPLACE ".xml" ".c" filename ${filename})
		set (out_file ${OUTDIR}/${filename})
		list (APPEND OUT_C ${out_file})

		add_custom_command (
		OUTPUT
			${out_file}
		COMMAND
			${GRESOURCE_COMPILE_EXECUTABLE}
			--target=${out_file}
			--generate
			--sourcedir=${SOURCEDIR}
			--c-name=${ARGS_CNAME}
			${in_file}
		DEPENDS
			${in_file}
		COMMENT
			"Generating ${filename}"
		VERBATIM
		)
	endforeach ()

	set (${output} ${OUT_C} PARENT_SCOPE)
endfunction ()
